package com.winsdom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winsdom.entity.SysOperationLog;
import com.winsdom.entity.SysOperationLogArchive;
import com.winsdom.mapper.SmsTemplateMapper;
import com.winsdom.service.*;
import com.winsdom.utils.IpAddressUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 陈文平
 * @CreateTime: 2025-05-14-11:43
 * @Description: 定时任务实现类
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor

public class ScheduledNotificationServiceImpl implements ScheduledNotificationService {


    private final SmsTemplateMapper smsTemplateMapper;
    private final SmsTemplateService smsTemplateService;
    private final ISysOperationLogService iSysOperationLogService;
    private final ISysOperationLogArchiveService iSysOperationLogArchiveService;

//    @Override
//    @Scheduled(cron = "${scheduled.collection.reminder.cron}")
//    public void scheduledSendCollectionReminder() {
//        log.info("开始执行定时缴款通知任务...");
//        List<Long> customerIds = paymentRecordMapper.selectNeedCollectionReminderCustomers();
//        if (customerIds.isEmpty()) {
//            log.info("无需要发送的缴款通知");
//            throw new IllegalArgumentException("无需要发送的催收通知");
//        }
//        customerIds.forEach(customerId -> {
//            try {
//                // 缴款通知
//                smsTemplateService.sendBillNotification(customerId);
//                log.info("客户ID={} 缴款通知发送成功", customerId);
//            } catch (Exception e) {
//                log.error("客户ID={}  缴款通知发送失败：{}", customerId, e.getMessage());
//            }
//        });
//        log.info("缴款通知通知任务执行结束");
//    }

    @Override
    @Scheduled(cron = "${scheduled.payment.reminder.cron}")
    @Transactional(rollbackFor = Exception.class)
    public void scheduledSendPaymentReminder() {
        log.info("开始执行定时催收通知任务...");
        List<Long> customerIds = smsTemplateMapper.selectNeedPaymentReminderCustomers();
        if (customerIds.isEmpty()) {
            log.info("无需要发送的催收通知");
            throw new IllegalArgumentException("无需要发送的催收通知");
        }
        customerIds.forEach(customerId -> {
            try {
                // 复用现有催收通知发送逻辑
                smsTemplateService.sendCollectReminder(customerId);
                // 发送成功后，更新客户通知配置中的当前次数（现有方法）
                smsTemplateService.updateCollectionNoticeTimesAndDate(customerId);
                log.info("客户ID={} 催收通知发送成功，当前次数+1", customerId);
            } catch (Exception e) {
                log.error("客户ID={} 催收通知发送失败：{}", customerId, e.getMessage());
            }
        });
        log.info("催收通知任务执行结束");
    }



    /**
     * 定时任务：归档旧的操作日志
     */

    @Scheduled(cron = "0 0 3 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void archiveOldOperationLogs() {
        log.info("开始执行定时归档操作日志任务...");
        LocalDateTime threshold = LocalDateTime.now().minusDays(180);

        QueryWrapper<SysOperationLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("operation_time", threshold);


        int pageSize = 1000;
        int current = 1;

        while (true) {
            Page<SysOperationLog> page = new Page<>(current, pageSize);
            IPage<SysOperationLog> logPage = iSysOperationLogService.page(page, queryWrapper);

            List<SysOperationLogArchive> archives = convertToArchive(logPage.getRecords());
            if (archives.isEmpty()) break;

            // 批量插入归档表
            iSysOperationLogArchiveService.saveBatch(archives);
            // 删除原数据
            iSysOperationLogService.removeByIds(archives.stream()
                    .map(SysOperationLogArchive::getId)
                    .collect(Collectors.toList()));

            current++;
        }

        log.info("操作日志归档任务执行完成");
    }




    private List<SysOperationLogArchive> convertToArchive(List<SysOperationLog> logs) {
        System.out.println("要归档的日志数量: " + logs.size());
        
        return logs.stream().map(log -> {
            SysOperationLogArchive archive = new SysOperationLogArchive();

            archive.setId(log.getId());
            archive.setOperationTime(log.getOperationTime());
            archive.setUserId(log.getUserId());
            

            if (log.getIpAddress() != null) {
                System.out.println("日志ID: " + log.getId() + ", IP地址不为空, 长度: " + log.getIpAddress().length);
                archive.setIpAddress(log.getIpAddress());
                
                try {
                    String ipStr = IpAddressUtil.bytesToIp(log.getIpAddress());
                    System.out.println("转换后的IP地址: " + ipStr);
                    

                    if (ipStr != null && !ipStr.isEmpty()) {
                        archive.setIpAddressStr(ipStr);
                    }
                } catch (Exception e) {
                    System.err.println("转换IP地址时出错: " + e.getMessage());
                }
            } else {
                System.out.println("警告: 日志ID: " + log.getId() + ", IP地址为null");

            }
            
            archive.setOperationFunction(log.getOperationFunction());
            archive.setOperationDescription(log.getOperationDescription());
            archive.setIsDeleted(log.getIsDeleted());

            return archive;
        }).collect(Collectors.toList());
    }

}

